package com.mdc.mansion.common.context;
import com.mdc.mansion.common.util.SerialToolKit;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
/**
 * @author chenmingdong
 *
 * 2016年1月29日
 */
public class AppContext {
	
	private static ApplicationContext applicationContext=null;
	/**
	 * 保存当前线程的请求序列
	 */
	private final static ThreadLocal<String> seqRequestThreadLocal=new ThreadLocal<String>();
	/**
	 * 保存当前线程的页数
	 */
	private final static ThreadLocal<Integer> pageNoThreadLocal=new ThreadLocal<Integer>();
	/**
	 * 保存当前线程每页显示数据的条数
	 */
	private final static ThreadLocal<Integer> pageSizeThreadLocal=new ThreadLocal<Integer>();
		
	/**
	 * 排序参数
	 */
	private final static ThreadLocal<String> orderByThreadLocal=new ThreadLocal<String>();

	/**
	 * 设置当前新的请求的请求序列号
	 */
	public static void setRequestSeq(){seqRequestThreadLocal.set(SerialToolKit.sequence());}
	
	
	public static void setApplicationContext(ApplicationContext context){
		applicationContext=context;
	}
	
	public static ApplicationContext getSpringApplicationContext(){
		return applicationContext;
	}
	/**
	 * 获取当前请求（线程）编号
	 * @return
	 */
	public static String getRequestSeq(){
		if(StringUtils.isEmpty(seqRequestThreadLocal.get())){
			return "RSEQRSEQ";
		}
		return "RSEQ"+seqRequestThreadLocal.get();
	}
	/**
	 * 清除当前请求（线程）编号
	 */
	public static void clearRequestSeq(){seqRequestThreadLocal.remove();}
	
	/**
	 * 设置当前线程的页数
	 * @param pageNo
	 */
	public static void setPageNo(int pageNo){pageNoThreadLocal.set(pageNo);}
	
	/**
	 * 获取当前线程的页数
	 * @return
	 */
	public static int getPageNo(){return pageNoThreadLocal.get();}
	/**
	 * 清除当前线程页数
	 */
	public static void clearPageNo(){pageNoThreadLocal.remove();}
	/**
	 * 设置当前线程行数
	 * @param pageSize
	 */
	public static void setPageSize(int pageSize){pageSizeThreadLocal.set(pageSize);}
	/**
	 * 获得当前线程行数
	 * @return
	 */
	public static int getPageSize(){return pageSizeThreadLocal.get();}
	
	/**
	 * 清除当前线程行数
	 */
	public static void clearPageSize(){pageSizeThreadLocal.remove();}

	
	public static void setOrderBy(String orderBy){orderByThreadLocal.set(orderBy);}
	
	public static String getOrderBy(){return orderByThreadLocal.get();}
	
	public static void clearOrderBy(){orderByThreadLocal.remove();}
	
	public static void clearContext(){
		clearPageNo();
		clearPageSize();
		clearOrderBy();
		clearRequestSeq();
	}
	
	public static void setContext(int pageNo,int pageSize,String orderBy){
		setPageNo(pageNo);
		setPageSize(pageSize);
		setOrderBy(orderBy);
		setRequestSeq();
	}
}
